import router from "@/router/route";
import axios from "axios";

const defaultConfig = {
  baseURL: `${import.meta.env.VITE_APP_COMMON_API_BASE_URL}/shale`,
  timeout: 10000, // 请求超时时间
  headers: {
    "Content-Type": "application/json",
  },
};

const defaultRequestInterceptorCallback = (config) => {
  const token = localStorage.getItem("jwtToken");
  console.log(token, config);
  if (token) {
    config.headers.Authorization = `${token}`;
  }
  return config;
};

const defaultResponseInterceptorCallback = (response) => {
  console.log("response", response.data);
  if ([401, 403].includes(response.data.code)) {
    router.push(`/${import.meta.env.VITE_APP_CAR_OR_OLDMAN}/login`);
  }
  return response;
};

const generateAxiosInstance = (
  config = defaultConfig,
  requestInterceptorCallback = defaultRequestInterceptorCallback,
  responseInterceptorCallback = defaultResponseInterceptorCallback
) => {
  const axiosInstance = axios.create(config);

  axiosInstance.interceptors.request.use(
    requestInterceptorCallback,
    (error) => {
      return Promise.reject(error);
    }
  );

  axiosInstance.interceptors.response.use(
    responseInterceptorCallback,
    (error) => {
      if (error.response && error.response.status === 401) {
      }
      return Promise.reject(error);
    }
  );

  return axiosInstance;
};

/**
 * 登录注册的 request
 */
const oldmanLoginRequest = generateAxiosInstance(
  {
    baseURL: `${import.meta.env.VITE_APP_OLDMAN_API_BASE_URL}`,
    timeout: 10000, // 请求超时时间
    headers: {
      "Content-Type": "application/json",
    },
  },
  (config) => {
    return config;
  },
  (response) => {
    return response;
  }
);

/**
 * 通用的 request
 */
const oldmanCommonRequest = generateAxiosInstance({
  baseURL: `${import.meta.env.VITE_APP_OLDMAN_API_BASE_URL}`,
  timeout: 10000, // 请求超时时间
  headers: {
    "Content-Type": "application/json",
  },
});

const oldmanUploadRequest = async (path: string, data) => {
  // console.log("file", data);
  const token = localStorage.getItem("jwtToken");
  const res = await axios.post(
    `${import.meta.env.VITE_APP_OLDMAN_API_BASE_URL}/provider/provider/${path}`,
    data,
    {
      headers: {
        "Content-Type": `multipart/form-data;`, // 让axios使用正确的Content-Type
        Authorization: token,
      },
    }
  );
  return res;
};

export { oldmanCommonRequest, oldmanLoginRequest, oldmanUploadRequest };
